//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 张远文 on 16/4/26.
//  Copyright © 2016年 张远文. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        
        //加载授权网页
        loadOAuthPage()
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
    
    private func loadOAuthPage() {
       
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
    
    //MARK: 按钮监听方法
    @objc private func close() {
      
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount() {
       
        let jsString = "document.getElementById('userId').value = '15820590464' , document.getElementById('passwd').value = 'wen12580';"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    private func setupUI() {
       
        //增加导航栏按键
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(fullAccount))
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

/*
 <NSMutableURLRequest: 0x7fcb18560590> { URL: https://api.weibo.com/oauth2/authorize?client_id=859066028&redirect_uri=http://www.itcast.cn }
 <NSMutableURLRequest: 0x7fcb1a90ea20> { URL: https://api.weibo.com/oauth2/authorize?client_id=859066028&redirect_uri=http://www.itcast.cn# }
 <NSMutableURLRequest: 0x7fcb184f5360> { URL: https://api.weibo.com/oauth2/authorize?client_id=859066028&redirect_uri=http://www.itcast.cn# }
 <NSMutableURLRequest: 0x7fcb1aa18380> { URL: https://api.weibo.com/oauth2/authorize }
 <NSMutableURLRequest: 0x7fcb185a1f20> { URL: https://api.weibo.com/oauth2/authorize# }
 <NSMutableURLRequest: 0x7fcb1aa356d0> { URL: https://api.weibo.com/oauth2/authorize }
 <NSMutableURLRequest: 0x7fcb1aa426d0> { URL: http://www.itcast.cn/?code=5c0e3ac45a2c6421e8737ac86a0ad55a }
 <NSMutableURLRequest: 0x7fcb1a99dba0> { URL: about:blank }
 <NSMutableURLRequest: 0x7fcb1a8e4b90> { URL: about:blank }
 <NSMutableURLRequest: 0x7fcb1ac0a100> { URL: jsbridge://device/qqVersion#1 }

 */

//类扩展,专门处理协议的代理方法
extension OAuthViewController : UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //过滤掉空的地址
        guard let urlString = request.URL?.absoluteString else {
            
            return false
        }
        
        //前缀为 https://api.weibo.com 的地址,正常显示
        if urlString.hasPrefix("https://api.weibo.com") {
            
            return true
        }
        
        //过滤掉前缀不是为 http://www.itcast.cn 的回调地址
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        //过滤掉没有带参数的地址
        guard let queue = request.URL?.query else {
            return false
        }
        
        //截取code字符串
        let codeStr = "code="
        let code = queue.substringFromIndex(codeStr.endIndex)
        
        //利用code请求token
        UserAccountViewModel().loadAccessToken(code) { (error) in
            
            if error != nil {
                
                SVProgressHUD.showWithStatus("网络异常,获取用户信息失败")
                return
            }
            
            self.dismissViewControllerAnimated(false, completion: {
                
                //切换页面通知
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewController, object: "Welcome")
            })
        }
        
        return false
    }
}
